package com.bookkeeping.cn;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bookkeeping.cn.databinding.ActivityLoginBinding;
import com.bookkeeping.cn.util.CodeUtils;
import com.bookkeeping.cn.util.LoadingUtils;
import com.bookkeeping.cn.util.OkHttpUtil;
import com.bookkeeping.cn.util.URLUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding binding;
    private EditText usernameEt;
    private EditText passwordEt;
    private Button loginBt;
    private EditText verifyEt;
    private ImageView verifyCodeIv;
    private TextView reTv;
    private CodeUtils codeUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initViews();
        initCaptcha();
        setupListeners();

        // 检查是否已登录
        checkLoginStatus();
    }

    private void initViews() {
        usernameEt = findViewById(R.id.username_et);
        passwordEt = findViewById(R.id.password_et);
        loginBt = findViewById(R.id.login_bt);
        verifyEt = findViewById(R.id.verify_code_et);
        verifyCodeIv = findViewById(R.id.verify_code_iv);
        reTv = findViewById(R.id.re_tv);
    }

    private void initCaptcha() {
        codeUtils = CodeUtils.getInstance();
        refreshCaptcha();
    }

    private void refreshCaptcha() {
        Bitmap captchaBitmap = codeUtils.createBitmap();
        verifyCodeIv.setImageBitmap(captchaBitmap);
    }

    private void setupListeners() {
        // 验证码图片点击刷新
        verifyCodeIv.setOnClickListener(v -> refreshCaptcha());

        // 登录按钮点击事件
        loginBt.setOnClickListener(v -> attemptLogin());

        // 注册按钮点击事件
        reTv.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }

    private void checkLoginStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences("token_file", MODE_PRIVATE);
        URLUtil.TOKEN = sharedPreferences.getString("token", "");
        if (!TextUtils.isEmpty(URLUtil.TOKEN)) {
            navigateToMain();
        }
    }

    private void attemptLogin() {
        String username = usernameEt.getText().toString().trim();
        String password = passwordEt.getText().toString().trim();
        String verifyCode = verifyEt.getText().toString().trim();

        if (TextUtils.isEmpty(username)) {
            showToast("用户名必须填写");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            showToast("密码必须填写");
            return;
        }

        if (TextUtils.isEmpty(verifyCode)) {
            showToast("验证码必须填写");
            return;
        }

        // 验证验证码
        if (!verifyCode.equalsIgnoreCase(codeUtils.getCode())) {
            showToast("验证码错误");
            refreshCaptcha();
            return;
        }

        performLogin(username, password);
    }

    private void performLogin(String username, String password) {
        LoadingUtils.showLoading(this);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", username);
        jsonObject.put("password", password);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json;charset=utf-8"),
                jsonObject.toJSONString()
        );

        Request request = new Request.Builder()
                .url(URLUtil.LOGIN)
                .post(requestBody)
                .build();

        OkHttpUtil.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    LoadingUtils.hideLoading();
                    showToast("网络请求失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (Response responseCopy = response) {
                    String responseStr = responseCopy.body().string();
                    JSONObject responseJson = JSON.parseObject(responseStr);
                    LoadingUtils.hideLoading();
                    runOnUiThread(() -> {
                        LoadingUtils.hideLoading();
                        showToast(responseJson.getString("message"));

                        if (responseJson.getInteger("code") == 1) {

                            URLUtil.TOKEN = "Bearer " + responseJson.getString("content");
                            SharedPreferences.Editor editor = getSharedPreferences("token_file", MODE_PRIVATE).edit();
                            editor.putString("token", URLUtil.TOKEN);
                            editor.apply();
                            navigateToMain();
                        } else {
                            // 登录失败时刷新验证码
                            refreshCaptcha();
                        }
                    });
                } catch (Exception e) {
                    runOnUiThread(() -> {
                        LoadingUtils.hideLoading();
                        showToast("响应解析错误");
                    });
                }
            }
        });
    }

    private void navigateToMain() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}